<template>
  <div
    ref="scrollContainer"
    class="scroll-container"
    @wheel.prevent="handleScroll"
  >
    <div
      ref="scrollWrapper"
      class="scroll-wrapper"
      :style="{
        transform: `translateX(${left}px)`
      }"
    >
      <slot />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const emit = defineEmits(['scroll'])

const scrollContainer = ref()
const scrollWrapper = ref()
const left = ref(0)

const handleScroll = (e) => {
  const eventDelta = e.wheelDelta || -e.deltaY * 40
  const $container = scrollContainer.value
  const $containerWidth = $container.offsetWidth
  const $wrapper = scrollWrapper.value
  const $wrapperWidth = $wrapper.offsetWidth

  if (eventDelta > 0) {
    left.value = Math.min(0, left.value + eventDelta)
  } else {
    if ($containerWidth - left.value < $wrapperWidth) {
      left.value = Math.max($containerWidth - $wrapperWidth, left.value + eventDelta)
    }
  }
  emit('scroll')
}

const moveToTarget = (currentTag) => {
  const $container = scrollContainer.value
  const $containerWidth = $container.offsetWidth
  const $wrapper = scrollWrapper.value
  const $wrapperWidth = $wrapper.offsetWidth

  const tagList = Array.from($wrapper.children)
  let firstTag = null
  let lastTag = null

  if (tagList.length > 0) {
    firstTag = tagList[0]
    lastTag = tagList[tagList.length - 1]
  }

  if (firstTag === currentTag) {
    left.value = 0
  } else if (lastTag === currentTag) {
    left.value = $containerWidth - $wrapperWidth
  } else {
    const targetIndex = tagList.findIndex(item => item === currentTag)
    const prevTag = tagList[targetIndex - 1]
    const nextTag = tagList[targetIndex + 1]

    const afterNextTagOffsetLeft = nextTag ? nextTag.offsetLeft + nextTag.offsetWidth + 4 : 0

    const beforePrevTagOffsetLeft = prevTag ? prevTag.offsetLeft - 4 : 0

    if (afterNextTagOffsetLeft > $containerWidth - left.value) {
      left.value = -(afterNextTagOffsetLeft - $containerWidth)
    } else if (beforePrevTagOffsetLeft < -left.value) {
      left.value = -beforePrevTagOffsetLeft
    }
  }
}

defineExpose({
  moveToTarget
})
</script>

<style lang="scss" scoped>
.scroll-container {
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  width: 100%;

  .scroll-wrapper {
    position: absolute;
    transition: transform 0.3s ease-in-out;
  }
}
</style>
